import redis

from shop.conf import redis_host, redis_port


class RedisUtil:

    def __init__(self, db=0):
        self.rds = redis.StrictRedis(db=db, decode_responses=True, host=redis_host, port=redis_port)

    def set_str(self, redis_key, value, expire_second=0):
        '''
        设置redis字符串
        :param redis_key:
        :param value:
        :param expire_second:
        :return:
        '''
        if expire_second:
            self.rds.set(redis_key, value, ex=expire_second)
        else:
            self.rds.set(redis_key, value)

    def get_str(self, redis_key):
        '''
        获取redis字符串
        :param redis_key:
        :return:
        '''
        return self.rds.get(redis_key)

    def set_list(self, redis_key, one_list, expire_second=0):
        '''
        设置一个新list，如果这个list已经存在，则执行添加操作
        :param redis_key:
        :param one_list:
        :param expire_second:
        :return:
        '''
        pipe = self.rds.pipeline()
        for one in one_list:
            pipe.rpush(redis_key, one)
        if expire_second:
            pipe.expire(redis_key, expire_second)
        pipe.execute()

    def get_list(self, redis_key):
        '''
        获取一个list
        :param redis_key:
        :return:
        '''
        redis_key_len = self.rds.llen(redis_key)
        if redis_key_len:
            return self.rds.lrange(redis_key, 0, redis_key_len)
        else:
            return []

    def get_set(self, redis_key):
        '''
        获取set 数据
        :param redis_key:
        :return:
        '''
        all_members = self.rds.smembers(redis_key)
        print(type(all_members))
        members_list = []
        for one in all_members:
            members_list.append(one)
        return members_list

    #
    #
    # hash结构的数据方法
    #
    #

    def get_hash(self, redis_key):
        """
        获取所有hash数据
        :param redis_key:
        :return:
        """
        one_dict = self.rds.hgetall(redis_key)
        return one_dict

    def get_hash_one_key(self, redis_key, one_key):
        """
        获取hash中的一个key的值
        :param redis_key: str
        :param one_key: str
        :return:
        """
        return self.rds.hget(redis_key, one_key)

    def set_hash(self, redis_key, one_dict, expire_seconds=0):
        """
        设置hash数据
        :param redis_key:
        :param one_dict:
        :return:
        """
        pipe = self.rds.pipeline()
        for key, value in dict(one_dict).items():
            pipe.hset(redis_key, key, value)
        if expire_seconds:
            pipe.expire(redis_key, expire_seconds)
        pipe.execute()

    def get_hash_len(self, redis_key):
        """
        获取hash结构的数据长度
        :param redis_key:
        :return:
        """
        return self.rds.hlen(redis_key)

    def expire_reids_key(self, redis_key, expire_seconds):
        """
        设置过期时间
        :param redis_key:
        :return:
        """
        self.rds.expire(redis_key, expire_seconds)
